# 登录注册controller层
from flask import Blueprint, request, jsonify
import json
from utils import Token
import service.LoginService as LoginService

# 创建login蓝图
login = Blueprint('login', __name__)


# 用户名登录
@login.route('/login/default', methods=['POST'])
def login_default():
    data = request.get_data()
    data = json.loads(data)
    userName = data['userName']
    passWord = data['passWord']
    result = LoginService.service_login_default(userName, passWord)
    if result['success']:
        token_msg = Token.generate_token(result['userInfo']['uuid'])
        result['token'] = token_msg[0]
        # 测试用语句，打印Token值
        # print(token_msg[0])
    return jsonify(result)


# 邮箱登录
@login.route('/login/email', methods=['POST'])
def login_email():
    data = request.get_data()
    data = json.loads(data)
    email = data['email']
    passWord = data['passWord']
    result = LoginService.service_login_email(email, passWord)
    if result['success']:
        token_msg = Token.generate_token(result['userInfo']['uuid'])
        result['token'] = token_msg[0]
    return jsonify(result)


# 注册
@login.route('/register', methods=['POST'])
def login_register():
    data = request.get_data()
    data = json.loads(data)
    email = data['email']
    userName = data['userName']
    passWord = data['passWord']
    # 验证码
    captcha = data['captcha']
    result = LoginService.service_login_register(email, userName, passWord, captcha)
    return result


# 找回密码
@login.route('/findMyPassword', methods=['POST'])
def login_forgotPassword():
    data = request.get_data()
    data = json.loads(data)

    email = data['email']
    # 验证码
    captcha = data['captcha']
    newPassword = data['newPassword']

    result = LoginService.service_login_forgotPassword(email, captcha, newPassword)
    return result


# 发送验证码
@login.route('/sendCaptcha', methods=['GET'])
def login_sendCaptcha():
    email = request.args.get('email', type=str, default=None)
    result = LoginService.service_login_sendCaptcha(email)
    return result
